#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os,getopt,sys
import time
from libs.data import VERSION,PATHS_PLUGIN,PLUGIN,CONF,VERSION
from libs.loader import load_string_to_module
from libs.config import PluginsConfig
from cmd import Cmd
def banner():
    msg ='''
         ____         __     _____           _   _             _         _ _  
        / ___|  __ _ / _| __|_   _|__   ___ | | | |__  _   _  | | ____ _| (_)
        \___ \ / _` | |_ / _ \| |/ _ \ / _ \| | | '_ \| | | | | |/ / _` | | | 
        ___) | (_| |  _|  __/| | (_) | (_) |  | | |_)  |  |_| | | < (_| | | | 
        |____/ \__,_|_|  \___||_|\___/ \___/|_| |_.__/ \__, | |_|\_\__,_|_|_|
                                                        |___/
        ''' .format(VERSION)
    return msg
def search(config:dict):
    _plugins = []
    for root,dirs,files in os.walk(PATHS_PLUGIN):
        files = filter(lambda x: not x.startswith("__") and x.endswith(".py")and x.split(".")[0] == config.get("plugin","") ,
        files)
        _plugins.extend(map(lambda x: os.path.join(root,x),files))
    for plugin in _plugins:
        with open(plugin,"r",encoding="utf-8") as f:
            model = load_string_to_module(f.read())
            #PLUGIN.append(model)
            return model
def start(config:dict):
    try:
        p = search(config)
        p.execute(config)
        '''
        for p in PLUGIN:
            p.execute(config)
        '''
    except Exception as e:
        print(e)
class Cli(Cmd):
    def __init__(self):      
        os.system("cls")
        Cmd.__init__(self)
        banner = '''
            _______  _______ _____ _   _ ____  
            | ____\ \/ /_   _| ____| \ | |  _ \\
            |  _|  \  /  | | |  _| |  \| | | | |
            | |___ /  \  | | | |___| |\  | |_| |
            |_____/_/\_\ |_| |_____|_| \_|____/
        '''          
        self.intro = banner
        self.prompt = 'SafeToolPlugins>> '
        self.pc = PluginsConfig()
    def do_help(self,param):
        print('Help Infomation:')
        for p in self.pc.get_plugins():
            print('%-4s%2s%s'%(' ','plugin: ',p))
    def do_info(self,param):
        name = param
        info = {}
        for p in self.pc.get_plugins():
            if name == p:
                info = self.pc.get_info(name)
                print('%-4s%2s%s'%(' ','plugin: ',p))
                print('%-4s%2s%s'%(' ','name: ',info["name"]))
                print('%-4s%2s%s'%(' ','des: ',info["des"]))
                print('%-4s%2s%s'%(' ','require: ',info["require"]))
    def do_exec(self,param):
        try:
            if param.find("_") >= 0:
                CONF["plugin"] = param.split("_")[0]
                if param.find(",") >=0:
                    params = param.split("_")
                    plist = params[1].split(",")
                    odds = []
                    evens = []
                    if len(plist)%2 == 0:
                        odds = [plist[x] for x in range(0,len(plist)) if x%2 == 0 ]
                        evens = [plist[x] for x in range(0,len(plist)) if x%2 != 0 ]
                        CONF["kwargs"] = dict(zip(odds,evens))
                        start(CONF)
                else:
                    CONF["args"] = param.split("_")[1]
                    start(CONF)
            else:
                CONF["plugin"] = param
                start(CONF)
        except Exception as e:
            print(e)
    def do_exit(self,param):
        print("Exit!")
        sys.exit()
    def default(self,param):
        print("order is not exit ! please enter help!")

if __name__ == "__main__":
    cli = Cli()
    cli.cmdloop()